<template>
  <t-skeleton :loading="loading">
    <!-- 内容 -->
    <template v-if="contractDetails.id">
      <div style="margin-bottom: var(--td-comp-margin-s)">
        <t-button v-permission="['system:single-product-contract:update']" v-if="contractDetails.result !=2&&contractDetails.result !=1" @click="handleOpenDialog('update', { id: contractDetails.id })"> 编辑合同 </t-button>
        <t-button v-permission="['system:single-product-contract:approval']" v-if="contractDetails.result == null || contractDetails.result == 3|| contractDetails.result == 4" @click="handleApprove"> 提交审核 </t-button>
        <span v-if="contractDetails.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(contractDetails.result - 1).theme">{{
          getTagThemeAndLabel(contractDetails.result - 1).label
        }}</t-tag>
      </span>
      </div>      
      <t-descriptions  bordered :column="4">
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>收货人</span>
          </template>
          {{ contractDetails.consignee }}
        </t-descriptions-item>
        <t-descriptions-item :span="3">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>收货地址</span>
          </template>
          {{ contractDetails.deliverGoodsAddress }}
        </t-descriptions-item>
        
        <t-descriptions-item   >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>送货时间</span>
          </template>
          {{ dayjs(contractDetails.deliverGoodsTime).format('YYYY-MM-DD') }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>产品合同总价</span>
          </template>
          {{ contractDetails.productContractPrice }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>已收金额</span>
          </template>
          {{ contractDetails.amountCollected }}
        </t-descriptions-item>
        <t-descriptions-item label="下单时间">
          {{ contractDetails.placeAnOrderTime?dayjs(contractDetails.placeAnOrderTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="送柜子时间">
          {{ contractDetails.songGuiziTime?dayjs(contractDetails.songGuiziTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="验收时间">
          {{ contractDetails.acceptanceCheckTime?dayjs(contractDetails.acceptanceCheckTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="合同文件" :span="4">
          <upload v-model:files="contractDetails.fileUrl" multiple disabled v-if="contractDetails.fileUrl && Array.isArray(contractDetails.fileUrl)"/>
        </t-descriptions-item>
       
      </t-descriptions>


    </template>
    <!-- 空 -->
    <t-empty v-else style="margin: 100px">
      <template #action>
        <t-button
          v-permission="['system:single-product-contract:create']"
          @click="
            handleOpenDialog('create', {
              id: orderDetails.id,
              orderId: orderId,
              fileUrl: [],
              consignee: orderDetails.name,
              deliverGoodsAddress: propertyInfoList.find((item) => item.id === orderDetails.propertyName)?.name + (orderDetails.address?orderDetails.address:'')
            })
          "
        >
          新建合同
        </t-button>
      </template>
    </t-empty>
    <!-- 自定义对话框 -->
    <contract-dialog ref="customDialogRef" @request-success="handleDialogRequestSuccess" :company-id="orderDetails.companyId" />
  </t-skeleton>
    <!-- 粘性审批对话框 -->
    <sticky-approve-dialog ref="stickyApproveDialogRef21" :order-id="orderId" approve-type="21" />
    <sticky-approve-dialog ref="stickyApproveDialogRef27" :order-id="orderId" approve-type="27" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import { singleProductContractCRUD, approvalSingleProductContract } from '@/api/order/single'
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import { useDictionaryStore } from '@/store';

import ContractDialog from './ContractDialog.vue';
import { propertyManageCRUD } from '@/api/config/property';

interface TagThemeAndLabel {
  theme: 'warning' | 'success' | 'danger' | 'default';
  label: string;
}

// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'orderDetails',
  },
});
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 将原有的 orderDetails 替换为 details
const orderDetails = details;

const orderId = details.value.orderId || details.value.id
console.log(orderId,'orderid');

// // 订单详情
// const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 加载状态
const loading = ref(false);
// 合同详情
const contractDetails = ref<Record<string, any>>({});
// 整装合同id
const zzContractId = ref()
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 处理获取合同详情
const handleGetContractDetails = () => {
  loading.value = true;
  const params = {
    orderId: orderId,
  };
  singleProductContractCRUD.page(params)
    .then((data) => {
      // if (data) contractDetails.value = data.list[0] || {};
      if(data.total>0) {
        zzContractId.value = data.list[0].id
        handleGetContractZheng({id:data.list[0].id})
      } else {
        contractDetails.value={}
      } 
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
handleGetContractDetails();
const handleGetContractZheng = (params:Record<string,any>) =>{
  singleProductContractCRUD.get(params).then(res=>{
    res.fileUrl = JSON.parse(res.fileUrl)
    contractDetails.value=res    
  })
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleGetContractDetails();
  if (result.mode === 'update') handleGetContractDetails();
};
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: number): TagThemeAndLabel => {
  const map: TagThemeAndLabel[] = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 提交审核
const handleApprove = () =>{
  const params = {
    orderId:orderId,
    id:orderDetails.value.id
  }
  approvalSingleProductContract(params).then(res => {
    MessagePlugin.success('提交审核成功');
    handleGetContractDetails();
  }).catch(({ message }) => {
      MessagePlugin.error(message);
    })
    
}
// 粘性审批对话框ref
const stickyApproveDialogRef21 = useTemplateRef('stickyApproveDialogRef21');
const stickyApproveDialogRef27 = useTemplateRef('stickyApproveDialogRef27');
onMounted(() => {
  const { approveType } = orderDetails.value;
  if (approveType === '21') stickyApproveDialogRef21.value.open();
  if (approveType === '27') stickyApproveDialogRef27.value.open();
});
</script>

<style lang="less" scoped>
.text-only-cascader {
  :deep(.t-input__suffix-icon) {
    display: none;
  }
  
}
</style>
